package com.heima.service.impl;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.domain.Patient;
import com.heima.domain.Users;
import com.heima.domain.UsersAccount;
import com.heima.dto.LoginDto;
import com.heima.mapper.PatientMapper;
import com.heima.mapper.UsersAccountMapper;
import com.heima.mapper.UsersMapper;
import com.heima.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.vo.LoginTokenVo;
import com.heima.vo.LoginVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 小程序用户 服务实现类
 * </p>
 *
 * @author 黑马程序员
 * @since 2023-01-29
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Autowired
    private UsersMapper mapper;
    @Autowired
    private UsersAccountMapper usersAccountMapper;
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录
     *
     * @param code
     * @return
     */
    @Override
    public LoginVo getOpenId(String code) {
        if (StringUtils.isEmpty(code)) {
            throw new RuntimeException("参数不能为空");
        }
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:9090/sns/jscode2session";
        url += "?appid=wxe6f0c12631e361d0";
        url += "&secret=6cb71ccff4a8bb85c153ad6ec996855c";
        url += "&js_code=" + code;
        url += "&grant_type=authorization_code";
        Map response = restTemplate.getForObject(url, Map.class);
        if (response == null) {
            throw new RuntimeException("微信调用异常");
        }
        Object errcode = response.get("errcode");
        Object openid = response.get("openid");
        LoginVo vo = new LoginVo();
        vo.setOpenId((String) openid);
        return vo;
    }

    /**
     * 登录鉴权
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public LoginTokenVo register(LoginDto dto) {
        if (StringUtils.isEmpty(dto)) {
            throw new RuntimeException("参数不能为空");
        }
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getPhone, dto.getPhone());
        wrapper.eq(Users::getOpenId, dto.getOpenId());
        Users users = mapper.selectOne(wrapper);
        Map<String, Object> payload = new HashMap<>();
        if (users == null) {
            Users users1 = new Users();
            BeanUtils.copyProperties(dto, users1);
            int insert = mapper.insert(users1);
            if (insert == 0) {
                throw new RuntimeException("新增失败");
            }
            UsersAccount usersAccount = new UsersAccount();
            usersAccount.setUserId(users1.getId());
            usersAccount.setBalance(0);
            int insert1 = usersAccountMapper.insert(usersAccount);
            if (insert1 == 0) {
                throw new RuntimeException("账户插入失败");
            }
            Patient patient = new Patient();
            patient.setUserId(users1.getId());
            patient.setAddress(dto.getCountry() + " " + dto.getProvince() + " " + dto.getCity());
            patient.setCardNumber("");
            patient.setCardType(0);
            patient.setIsDefault(1);
            patient.setName(dto.getNickName());
            patient.setPhone(dto.getPhone());
            patient.setTags("本人");
            int insert2 = patientMapper.insert(patient);
            if (insert2 == 0) {
                throw new RuntimeException("新增失败2");
            }
            payload.put("id", users1.getId());
            payload.put("openId", users1.getOpenId());
            String token = JWTUtil.createToken(payload, "code".getBytes());
            LoginTokenVo vo = new LoginTokenVo();
            vo.setToken(token);
            return vo;
        } else {
            payload.put("id", users.getId());
            payload.put("openId", users.getOpenId());
            String token = JWTUtil.createToken(payload, "code".getBytes());
            LoginTokenVo vo = new LoginTokenVo();
            vo.setToken(token);
            return vo;
        }
    }
}
